<script setup lang="ts">
  import {
    Tooltip,
    TooltipContent,
    TooltipTrigger,
    TooltipProvider
  } from '@renderer/components/ui/tooltip'
  import { motion } from 'motion-v'
  import { useI18n } from 'vue-i18n'
  import RegionSelector from '@renderer/components/RegionSelector.vue'
  import { ref } from 'vue'
  import { videoService } from '@renderer/services/video.service'
  import { useSettingsStore } from '@renderer/store/modules/settings.store'
  import { useRecordingStore } from '@renderer/store/modules/recording.store'

  const { ipc } = window
  const { t } = useI18n()
  const video = ref<HTMLVideoElement | null>(null)
  const regionSelector = ref<InstanceType<typeof RegionSelector> | null>(null)
  const isMenuOpen = ref(false)

  const settingsStore = useSettingsStore()
  const recordingStore = useRecordingStore()

  const startRecording = async () => {
    try {
      // 配置录制选项
      const displayMediaOptions: any = {
        video: {
          cursor: recordingStore.settings.captureMouse ? 'always' : 'never'
        },
        audio: recordingStore.settings.captureSystemAudio
          ? {
              echoCancellation: true,
              noiseSuppression: true,
              sampleRate: 44100
            }
          : false
      }

      // 根据录制类型设置不同的视频选项
      if (recordingStore.settings.captureType === 'window') {
        displayMediaOptions.video.displaySurface = 'window'
      } else if (recordingStore.settings.captureType === 'display') {
        displayMediaOptions.video.displaySurface = 'monitor'
      } else if (
        recordingStore.settings.captureType === 'region' &&
        recordingStore.settings.captureRegion.enabled
      ) {
        // 对于区域录制，可以使用 cropTarget API (这是一个实验性API)
        // 或者使用 canvas 方法来实现自定义区域录制
        displayMediaOptions.video.displaySurface = 'window'
      }

      // 请求屏幕共享
      navigator.mediaDevices
        .getDisplayMedia(displayMediaOptions)
        .then(async (stream) => {
          if (
            recordingStore.settings.captureType === 'region' &&
            recordingStore.settings.captureRegion.enabled
          ) {
            // 如果是区域录制，需要处理录制流
            stream = await processRegionStream(stream)
          }

          video.value!.srcObject = stream
          video.value!.onloadedmetadata = () => video.value!.play()
          // 保存流到存储
          recordingStore.setRecordingStream(stream)

          // 当用户停止共享时触发
          stream.getVideoTracks()[0].addEventListener('ended', () => {
            stopRecording()
          })

          // 创建媒体录制器
          const mimeType = 'video/webm;codecs=vp9'
          const mediaRecorder = new MediaRecorder(stream, { mimeType })

          // 保存录制器到存储
          recordingStore.setMediaRecorder(mediaRecorder)

          // 设置数据处理
          mediaRecorder.ondataavailable = (event) => {
            if (event.data && event.data.size > 0) {
              // 将数据块添加到存储
              recordingStore.addRecordedChunk(event.data)
            }
          }
          // 设置录制结束的处理
          mediaRecorder.onstop = async () => {
            // 创建视频URL
            const videoUrl = recordingStore.createVideoUrl()
            if (videoUrl) {
              console.log('录制完成，视频URL：', videoUrl)

              try {
                // 打开保存对话框
                const result = await ipc.record.saveVideo(videoUrl)

                if (result && result.success && result.filePath) {
                  // 根据文件扩展名决定输出格式
                  const fileExt = result.filePath.split('.').pop()?.toLowerCase() || 'mp4'
                  const outputFormat = fileExt === 'webm' ? 'webm' : 'mp4'

                  // 保存处理后的视频
                  const saveSuccess = await saveVideoToFile(videoUrl, result.filePath, outputFormat)

                  if (saveSuccess) {
                    console.log('视频保存成功:', result.filePath)
                  } else {
                    console.error('视频保存失败')
                  }
                }
              } catch (err) {
                console.error('保存视频失败:', err)
              }
            }
          }

          // 开始录制
          mediaRecorder.start(1000) // 每秒获取一次数据
        })
        .catch((err) => {
          console.error('屏幕录制失败:', err)
        })

      recordingStore.startRecording()
    } catch (err) {
      console.error('屏幕录制失败:', err)
      // 如果获取媒体失败，不应该开始计时
      if (recordingStore.isRecording) {
        recordingStore.stopRecording()
      }
    }
  }

  // 保存视频到指定路径
  const saveVideoToFile = async (
    videoUrl: string,
    filePath: string,
    outputFormat = 'mp4'
  ): Promise<boolean> => {
    try {
      // 处理视频
      const data = await videoService.processVideo(videoUrl, outputFormat)

      // 处理完成，向主进程发送保存请求
      const result = await ipc.record.saveProcessedVideo({ fileData: Array.from(data), filePath })

      // 清理资源
      videoService.unload()

      return result.success
    } catch (error) {
      console.error('处理视频失败:', error)
      return false
    }
  }

  // 处理区域录制流
  const processRegionStream = async (stream: MediaStream): Promise<MediaStream> => {
    // 创建一个 canvas 元素
    const canvas = document.createElement('canvas')
    const region = recordingStore.settings.captureRegion

    // 设置初始 canvas 尺寸
    canvas.width = region.width
    canvas.height = region.height

    const ctx = canvas.getContext('2d')
    if (!ctx) {
      return stream
    }

    // 创建一个视频元素作为源
    const videoElement = document.createElement('video')
    videoElement.srcObject = stream
    await videoElement.play()

    // 获取视频的实际尺寸
    const actualWidth = videoElement.videoWidth
    const actualHeight = videoElement.videoHeight
    console.log('视频实际尺寸:', { width: actualWidth, height: actualHeight })

    // 存储的设备像素比例
    const storedPixelRatio = region.devicePixelRatio || 1

    // 当前设备像素比例
    const currentPixelRatio = window.devicePixelRatio || 1

    // 计算调整后的坐标和尺寸
    let adjustedX = region.x
    let adjustedY = region.y
    let adjustedWidth = region.width
    let adjustedHeight = region.height

    // 如果存储的像素比和当前像素比不同，需要调整
    if (storedPixelRatio !== currentPixelRatio) {
      const ratio = storedPixelRatio / currentPixelRatio
      adjustedX *= ratio
      adjustedY *= ratio
      adjustedWidth *= ratio
      adjustedHeight *= ratio
    }

    // 计算实际绘制区域（考虑视频与屏幕尺寸的比例）
    const screenToVideoRatioX = actualWidth / window.innerWidth
    const screenToVideoRatioY = actualHeight / window.innerHeight

    const drawX = Math.round(adjustedX * screenToVideoRatioX)
    const drawY = Math.round(adjustedY * screenToVideoRatioY)
    const drawWidth = Math.round(adjustedWidth * screenToVideoRatioX)
    const drawHeight = Math.round(adjustedHeight * screenToVideoRatioY)

    // 调整 canvas 尺寸以匹配绘制区域
    canvas.width = drawWidth || region.width
    canvas.height = drawHeight || region.height

    console.log('区域录制详细信息:', {
      region,
      screen: { width: window.innerWidth, height: window.innerHeight },
      actualVideo: { width: actualWidth, height: actualHeight },
      pixelRatio: { stored: storedPixelRatio, current: currentPixelRatio },
      adjustedRegion: { x: adjustedX, y: adjustedY, width: adjustedWidth, height: adjustedHeight },
      screenToVideoRatio: { x: screenToVideoRatioX, y: screenToVideoRatioY },
      drawArea: { x: drawX, y: drawY, width: drawWidth, height: drawHeight }
    })

    // 清除 canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    // 定期将选定区域绘制到 canvas 上
    const drawInterval = setInterval(() => {
      if (!recordingStore.isRecording) {
        clearInterval(drawInterval)
        return
      }

      // 清除 canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height)

      // 绘制指定区域到 canvas
      try {
        ctx.drawImage(
          videoElement,
          drawX,
          drawY,
          drawWidth,
          drawHeight,
          0,
          0,
          canvas.width,
          canvas.height
        )
      } catch (err) {
        console.error('Canvas 绘制错误:', err, {
          drawArea: { x: drawX, y: drawY, width: drawWidth, height: drawHeight },
          canvas: { width: canvas.width, height: canvas.height },
          video: { width: videoElement.videoWidth, height: videoElement.videoHeight }
        })
      }
    }, 1000 / 30) // 30fps

    // 从 canvas 创建新的媒体流
    const canvasStream = canvas.captureStream(30)

    // 如果原始流有音频轨道，将其添加到新流
    const audioTracks = stream.getAudioTracks()
    if (audioTracks.length > 0) {
      canvasStream.addTrack(audioTracks[0])
    }

    // 在原始流停止时，清理资源
    stream.getVideoTracks()[0].addEventListener('ended', () => {
      clearInterval(drawInterval)
      videoElement.remove()
      canvas.remove()
    })

    return canvasStream
  }

  const stopRecording = () => {
    recordingStore.stopRecording()
  }

  // 处理区域选择事件
  const onSelectionComplete = () => {
    isMenuOpen.value = false
  }

  const onSelectionCancel = () => {
    isMenuOpen.value = false
    recordingStore.updateSettings({
      captureType: 'window',
      captureRegion: {
        ...recordingStore.settings.captureRegion,
        enabled: false
      }
    })
  }

  // 当选择器显示遮罩层时关闭菜单
  const onOverlayShown = () => {
    isMenuOpen.value = false
  }

  // 设置录制整个窗口
  const setRecordEntireWindow = () => {
    recordingStore.updateSettings({
      captureType: 'window',
      captureRegion: {
        ...recordingStore.settings.captureRegion,
        enabled: false
      }
    })
    isMenuOpen.value = false
  }

  // 设置录制区域
  const setRecordRegion = () => {
    recordingStore.updateSettings({
      captureType: 'region',
      captureRegion: {
        ...recordingStore.settings.captureRegion,
        enabled: true
      }
    })
    isMenuOpen.value = false
    regionSelector.value?.showOverlay()
  }
</script>

<template>
  <motion.div
    :initial="{ width: 120 }"
    :animate="{
      width: recordingStore.isRecording ? 165 : 120
    }"
    :transition="{ width: { duration: 0.2, ease: 'easeInOut' } }"
    class="p-2 rounded-md flex gap-2 items-center justify-end bg-muted"
  >
    <!-- 录制时间 -->
    <div
      v-if="recordingStore.isRecording"
      class="text-sm text-indigo-400 flex whitespace-nowrap items-center justify-center overflow-hidden"
    >
      {{ recordingStore.recordingTimeFormatted }}
    </div>

    <!-- 录制按钮 -->
    <TooltipProvider>
      <Tooltip v-if="recordingStore.isRecording">
        <TooltipTrigger>
          <button class="record-bar-button btn" @click="stopRecording">
            <i class="i-mynaui-stop-circle-solid text-red-500"></i>
          </button>
        </TooltipTrigger>
        <TooltipContent class="p-2 text-center">
          <p class="text-[10px]"> {{ t('recording-bar.stop-btn.tooltip') }} </p>
        </TooltipContent>
      </Tooltip>
      <Tooltip v-if="!recordingStore.isRecording">
        <TooltipTrigger>
          <button class="record-bar-button btn" @click="startRecording">
            <i class="i-mynaui-play-circle-solid"></i>
          </button>
        </TooltipTrigger>
        <TooltipContent class="p-2 text-center">
          <p class="text-[10px]"> {{ t('recording-bar.start-btn.tooltip') }} </p>
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>

    <!-- 区域选择按钮 -->
    <DropdownMenu v-model:open="isMenuOpen">
      <DropdownMenuTrigger as="button" class="flex items-center justify-center">
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger>
              <button
                class="record-bar-button btn"
                :class="{
                  'text-indigo-500':
                    recordingStore.settings.captureType === 'region' &&
                    recordingStore.settings.captureRegion.enabled
                }"
              >
                <i class="i-mynaui-crop"></i>
              </button>
            </TooltipTrigger>
            <TooltipContent class="p-2 text-center">
              <p class="text-[10px]">
                {{ t('recording-bar.region-btn.tooltip') }}
              </p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="center" :side-offset="10">
        <DropdownMenuGroup>
          <DropdownMenuItem @click="setRecordRegion">
            <i class="i-mynaui-crop mr-2"></i>
            {{ t('recording-bar.region-btn.tooltip') || '选择录制区域' }}
          </DropdownMenuItem>
          <DropdownMenuItem @click="setRecordEntireWindow">
            <i class="i-mynaui-desktop mr-2"></i>
            {{ t('recording-bar.window-btn.tooltip') || '选择录制窗口' }}
          </DropdownMenuItem>
        </DropdownMenuGroup>
      </DropdownMenuContent>
    </DropdownMenu>

    <!-- 视频选项按钮 -->
    <DropdownMenu>
      <DropdownMenuTrigger as="button" class="flex items-center justify-center">
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger>
              <button class="record-bar-button btn">
                <i v-if="settingsStore.cameraId" class="i-mynaui-video"></i>
                <i v-else class="i-mynaui-video-slash"></i>
              </button>
            </TooltipTrigger>
            <TooltipContent class="p-2 text-center">
              <p class="text-[10px]"> {{ t('recording-bar.camera-btn.tooltip') }} </p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="center">
        <DropdownMenuRadioGroup v-model="settingsStore.cameraId">
          <DropdownMenuRadioItem
            v-for="camera in settingsStore.getCameraList"
            :value="camera.id"
            :key="camera.id"
          >
            {{ camera.label }}
          </DropdownMenuRadioItem>
        </DropdownMenuRadioGroup>
      </DropdownMenuContent>
    </DropdownMenu>

    <!-- 音频选项按钮 -->
    <DropdownMenu>
      <DropdownMenuTrigger as="button" class="flex items-center justify-center">
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger>
              <button
                class="record-bar-button btn"
                :class="{ 'opacity-50': !recordingStore.settings.captureAudio }"
              >
                <i v-if="settingsStore.microphoneId" class="i-mynaui-microphone"></i>
                <i v-else class="i-mynaui-microphone-slash"></i>
              </button>
            </TooltipTrigger>
            <TooltipContent class="p-2 text-center">
              <p class="text-[10px]"> {{ t('recording-bar.microphone-btn.tooltip') }} </p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="center">
        <DropdownMenuRadioGroup v-model="settingsStore.microphoneId">
          <DropdownMenuRadioItem
            v-for="microphone in settingsStore.getMicrophoneList"
            :value="microphone.id"
            :key="microphone.id"
          >
            {{ microphone.label }}
          </DropdownMenuRadioItem>
        </DropdownMenuRadioGroup>
      </DropdownMenuContent>
    </DropdownMenu>

    <RegionSelector
      ref="regionSelector"
      class="absolute"
      @selection-complete="onSelectionComplete"
      @selection-cancel="onSelectionCancel"
      @overlay-shown="onOverlayShown"
    />

    <!-- 视频预览 -->
    <video
      ref="video"
      v-show="recordingStore.isRecording"
      class="w-[300px] aspect-video left-10 top-10 absolute"
    ></video>
  </motion.div>
</template>

<style lang="scss" scoped>
  .record-bar-button {
    @apply rounded-md flex items-center justify-center;
  }
</style>
